package com.cloudm.technician.ui.modules.personal.personal_center

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.cloudm.technician.R
import com.cloudm.technician.data.model.UploadTokenInfo
import com.cloudm.technician.data.model.User
import com.cloudm.technician.extensions.loadImage
import com.cloudm.technician.extensions.openActivity
import com.cloudm.technician.extensions.toast
import com.cloudm.technician.ui.base.BasePermissionsFragment
import com.cloudm.technician.ui.base.PicBottomDialogFragment
import com.cloudm.technician.ui.modules.common.about.AboutActivity
import com.cloudm.technician.ui.modules.common.login.LoginActivity
import com.cloudm.technician.ui.modules.personal.change_nick_name.ChangeNickNameActivity
import com.cloudm.technician.ui.modules.personal.change_password.ChangePasswordActivity
import com.cloudm.technician.ui.widget.OnceClickListener
import kotlinx.android.synthetic.main.fragment_personal_center.*
import java.io.File

/**
 * 作者: wesley
 * 时间: 2017/12/26
 * 描述: ui
 */
class PersonalCenterFragment : BasePermissionsFragment<PersonalCenterPresenter>(),
        PersonalCenterContract.View, PersonalCenterDialogFragment.OnDialogItemClickListener,
        PicBottomDialogFragment.OnItemClickListener {

    private var logo: String? = null

    override val resource: Int
        get() = R.layout.fragment_personal_center

    companion object {
        private const val TAG = "PersonalCenterFragment"
        private const val REQUEST_REQUEST_FOR_CHANGE_NICK_NAME = 1
        fun newInstance() = PersonalCenterFragment()
    }

    override fun initInject() {
        DaggerPersonalCenterComponent.builder().appComponent(
                appComponent).personalCenterPresenterModule(
                PersonalCenterPresenterModule(this)).build().inject(this)
    }

    override fun handleBundle(bundle: Bundle) {

    }

    override fun initVariables() {

    }

    override fun initViews(view: View) {
        presenter?.getUserInfo()
    }

    override fun initListener() {
        rlIconItem.setOnClickListener(OnItemClickListener())
        rlNickNameItem.setOnClickListener(OnItemClickListener())
        rlChangePasswordItem.setOnClickListener(OnItemClickListener())
        rlAboutdItem.setOnClickListener(OnItemClickListener())
        tvExitLogin.setOnClickListener(OnItemClickListener())
    }

    override fun userInfoLoadSuccess(user: User?) {
        user?.let {
            logo = it.logo
            tvAccount.text = it.mobile
            tvNickNameValue.text = it.nickname
            updateUserIcon(logo)
        }
    }


    override fun exitLogin() {
        val intent = Intent(mContext, LoginActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        }
        mContext.openActivity(intent)
    }


    private fun showUploadPicDialog() {
        val fragment = PicBottomDialogFragment.newInstance()
        fragment.listener = this
        fragment.show(childFragmentManager, TAG)
    }

    private fun showExitLoginDialog() {
        val fragment = PersonalCenterDialogFragment.newInstance()
        fragment.listener = this
        fragment.show(childFragmentManager, TAG)
    }

    private fun openChangeNickNameActivity() {
        startActivityForResult(Intent(mContext, ChangeNickNameActivity::class.java).apply {
            putExtras(Bundle().apply {
                putString("name", tvNickNameValue.text.toString())
            })
        }, REQUEST_REQUEST_FOR_CHANGE_NICK_NAME)
    }

    private fun openChangePasswordActivity() {
        mContext.openActivity(ChangePasswordActivity::class.java, false)
    }

    private fun openAboutActivity() {
        mContext.openActivity(AboutActivity::class.java, false)
    }

    override fun onExitLoginClick() {
        presenter?.exitLogin()
    }

    override fun takePic() {
        requestPermissionsForCamera()
    }

    override fun takeFromGalley() {
        requestPermissionFromGalley()
    }

    private inner class OnItemClickListener : OnceClickListener() {
        override fun onOnceClick(view: View) {
            when (view.id) {
                R.id.rlIconItem -> showUploadPicDialog()
                R.id.rlNickNameItem -> openChangeNickNameActivity()
                R.id.rlChangePasswordItem -> openChangePasswordActivity()
                R.id.rlAboutdItem -> openAboutActivity()
                R.id.tvExitLogin -> showExitLoginDialog()
            }
        }
    }


    private fun updateUserIcon(path: String?) {
        ivIcon.loadImage(path, R.mipmap.ic_login_user_icon)
    }

    private fun compressImage(path: String) {
        compressImageByLuban(path, onSuccess = { info ->
            presenter?.getUploadToken(info)
        }, onFailure = {
            mContext.toast(mContext.resources.getString(R.string.pic_upload_failure))
            updateUserIcon(logo)
        })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        when (requestCode) {
            REQUEST_REQUEST_FOR_CHANGE_NICK_NAME -> {
                tvNickNameValue.text = data?.extras?.getString("name")
            }
        }
    }

    override fun takePictureSuccess(path: String) {
        super.takePictureSuccess(path)
        updateUserIcon(path)
        compressImage(path)
    }

    override fun takeFromGalleySuccess(path: String) {
        super.takeFromGalleySuccess(path)
        updateUserIcon(path)
        compressImage(path)
    }

    override fun showTokenInfoEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.pic_upload_failure))
    }

    override fun updateUiByFlag(flag: Int) {
        updateUserIcon(logo)
    }

    override fun loadTokenInfoSuccess(info: UploadTokenInfo, file: File) {
        presenter?.uploadFile(info, file)
    }

    override fun showErrorMsg(errorMsg: String) {
        mContext.toast(errorMsg)
    }

    override fun picUploadFailure() {
        mContext.toast(mContext.resources.getString(R.string.pic_upload_failure))
    }

    override fun picUploadSuccess(url: String) {
        presenter?.uploadLogo(url)
    }

    override fun modifyLogoSuccess(url: String) {
        logo = url
        updateUserIcon(logo)
    }
}